/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fyx.web;

import java.io.IOException;
import java.util.Locale;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.fyx.linker.web.LinkerLocal;
import org.fyx.secure.ejb.SecureLocal;
import org.fyx.web.context.WebContext;
import org.fyx.web.context.WebPage;
import org.primefaces.model.MenuModel;

/**
 * Hlavní session beana.
 * 
 * @author xljan
 */
@ManagedBean(name = "man")
@SessionScoped
public class MainSessionBean {

    @EJB
    private SecureLocal secure;
    @EJB
    private LinkerLocal linker;
    String currentUrl = "";

    @PostConstruct
    public void postConstruct() {
        secure.logout();
    }
    
    /**
     * Po vyprseni session se uzivatel automaticky odhlasi.
     */
    @PreDestroy
    public void preDestroy() {
        secure.logout();
    }
    
    /**
     * Vrati aktualni vnitrni URL adresu
     * 
     * @return aktualni URL
     */
    public String getRequestUrl(){
        return WebContext.getRequestURL();
    }

    /**
     * Vrati model viceurovnoveho hlavniho menu.
     * Pokud tento model neexistuje, vytvori ho.
     * 
     * @return 
     */
    public MenuModel getMenuModel() {
        if (WebContext.getMenuModel() == null) {
            linker.recreateMenuModel();
        }
        return WebContext.getMenuModel();
    }

    /**
     * Vrati verzi systemu.
     * 
     * @return 
     */
    public String getVersion() {
        return Constants.FYX_VERSION;
    }

    /**
     * Nastaví jazyk do kontextu aktualniho klienta.
     * 
     * @param isoLenguage
     * @throws IOException 
     */
    public void setLenguage(String isoLenguage) {
        WebContext.getCurrentContext().setIsoLanguage(isoLenguage);
        WebPage.redirect(WebContext.getCurrentContext().getBaseUrl());
        linker.recreateMenuModel();
    }

    /**
     * Odesle vsechny zpravy ulozene v kontextu uzivatele.
     * Pouziva se pri redirect stranky, kdy by zpravy byly jinak zahozeny.
     */
    public void sendMessages() {
        for (FacesMessage msg : WebContext.getMessages()) {
            FacesContext.getCurrentInstance().addMessage("static_msg", msg);
        }
        WebContext.getMessages().clear();
    }

    /**
     * Presmeruje na urcitou stranku.
     * 
     * @param url
     * @throws IOException 
     */
    public void redirect(String url) throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect(url);
    }
}
